import com.agrm.model.common.dtos.BaseModel;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.lang.NonNull;

import java.time.LocalDateTime;

/**
 * aop，拦截所有业务操作，如果是保存或修改操作，如果参数是继承自AuditEntity的，则自动填充创建时间和更新时间
 */
public class AutoAuditMethodInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(@NonNull MethodInvocation invocation) throws Throwable {
        String method = invocation.getMethod().getName();
        if (method.equals("save") || method.equals("update")) {
            Object[] args = invocation.getArguments();
            if (args.length > 0) {
                Object arg0 = args[0];//首参
                if (arg0 instanceof BaseModel ae) {
                    AuthInfo authInfo = AuthInfo.current();
                    ae.setUpdatedBy(authInfo.username());
                    ae.setUpdatedTime(LocalDateTime.now());
                    if (method.equals("save")) {
                        ae.setCreatedBy(authInfo.username());
                        ae.setCreatedTime(LocalDateTime.now());
                    }
                }
            }
        }
        return invocation.proceed();
    }
}
